package v1

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"tapay-ws/pkg/app"
	"tapay-ws/pkg/errcode"
	"tapay-ws/pkg/service"
)

type UserConn struct{}

func NewUserConn() *UserConn {
	return &UserConn{}
}

func (*UserConn) SendMsg(c *gin.Context) error {
	var req service.SendMsgRequest
	if valid, errs := app.BindAndValid(c, &req); !valid {
		return errcode.InvalidParams.WithDetails(errs.Errors()...)
	}
	svc := service.New(c.Request.Context())
	msg := "Sent Success"
	conn := svc.GetConn(req.UserId, req.UserType)
	m := map[string]interface{}{
		"action": req.Action,
		"body":   req.Body,
	}
	b, err := json.Marshal(m)
	if err != nil {
		return err
	}
	if conn != nil {
		conn.WriteMessage(websocket.TextMessage, b)
	} else {
		msg = "User Disconnected"
	}
	response := app.NewResponse(c)
	response.ToResponse(msg)
	return nil
}
